//
//  DisposeViewController.m
//  TryShopping
//
//  Created by panquanReabam.com on 16/8/30.
//  Copyright © 2016年 RuiBen. All rights reserved.
//

#import "DisposeViewController.h"
#import "webCollectionViewCell.h"
#import "ZJSwitch.h"
#import "UIViewExt.h"
#import "HttpRequest.h"
#import "UIImageView+WebCache.h"
#import "RDVTabBarController.h"
#import "TimeView.h"
#import "VPImageCropperViewController.h"
#import "UpYun.h"
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
@interface DisposeViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UITextViewDelegate,UISearchBarDelegate,UIScrollViewDelegate,VPImageCropperDelegate,UICollectionViewDataSource,UICollectionViewDelegate,CLLocationManagerDelegate,UIActionSheetDelegate, UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIGestureRecognizerDelegate>
@property(nonatomic,retain)UIDatePicker* da;
@property(nonatomic,retain)UIDatePicker* da1;
@property(nonatomic,retain)UIDatePicker* da2;
@end

@implementation DisposeViewController
{
    TimeView*timeView;
    UIView*view;
    UITextView* tv;
    UILabel * label;
    UIImageView*images;
    UIView* myToolBar;
    UIScrollView*MYmainScroll;
    NSMutableArray *imageArray;
    UIView*imageView;
    NSMutableArray*imageList;
    NSUInteger ArrayCount;
}

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    self.title = self.titleName;
    self.view.backgroundColor=[UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     backColor,
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    MYmainScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, ScreenHeight)];
    [MYmainScroll setBackgroundColor: zuiqianhuiColor];
    MYmainScroll.delegate = self;
    MYmainScroll.userInteractionEnabled = YES;
    MYmainScroll.scrollEnabled = YES;
    MYmainScroll.showsVerticalScrollIndicator = FALSE;
    MYmainScroll.showsHorizontalScrollIndicator = FALSE;
    [self.view addSubview:MYmainScroll];
    
    myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:keyboardFot];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    [self update:@""];
    
    UIButton* registed = [[UIButton alloc] initWithFrame:CGRectMake(0,ScreenHeight-48 ,ScreenWidth, 48)];
    [registed setTitle:self.titleName forState:UIControlStateNormal];
    registed.backgroundColor=luseColor;
    [registed setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    registed.titleLabel.font=[UIFont systemFontOfSize:16];
    [registed addTarget:self action:@selector(GO:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registed];
    imageList=[[NSMutableArray alloc]init];
    
    
   
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:@"other" forKey:@"uploadType"];
    
    
    [HttpRequest requestData:@"Common/GetUpyunFormParams" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSString*policy=[severDataDict.dataDict objectForKey:@"policy"];
                NSString*signature=[severDataDict.dataDict objectForKey:@"signature"];
                NSString*action=[severDataDict.dataDict objectForKey:@"action"];
                [user setObject:signature forKey:@"signature"];
                [user setObject:policy forKey:@"policy"];
                [user setObject:action forKey:@"action"];
                [user synchronize];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];


}

- (void)update:(NSString *)str{
    
   
    view=[[UIView alloc]initWithFrame:CGRectMake(0, 10, ScreenWidth, 120)];
    view.backgroundColor=[UIColor whiteColor];
    view.layer.borderWidth = 0.40;
    view.layer.borderColor = qianhuiColor.CGColor;
    [MYmainScroll addSubview:view];
    tv=[[UITextView alloc]init];
    tv.frame=CGRectMake(20, 10, ScreenWidth-40, 90);
    tv.backgroundColor = [UIColor whiteColor];//设置它的背景颜色/Users/jiezsoft/Desktop/
    tv.scrollEnabled = YES;//是否可以拖动
    tv.delegate=self;
    tv.font = [UIFont fontWithName:@"Arial" size:15.0];//设置字体名字和字体大小
    tv.layer.borderWidth =0.0;
    CGColorSpaceRef registedSpace11 = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref111 = CGColorCreate(registedSpace11,(CGFloat[]){ 0, 0, 0, 0.3 });
    [tv.layer setBorderColor:tureBTncolorref111];//边框颜色
    tv.layer.cornerRadius =0;
    [view addSubview:tv];
    images=[[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 20, 16)];
    images.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
    [tv addSubview:images];
    label=[[UILabel alloc]init];
    label.frame =CGRectMake(23, 7, ScreenWidth-60, 14);
    label.text = @"备注";
    label.textColor=qianhuiColor;
    label.numberOfLines=0;
    label.font=[UIFont systemFontOfSize:14];
//    label.enabled = NO;//lable必须设置为不可用
//    label.backgroundColor = [UIColor clearColor];
    [tv addSubview:label];
    tv.inputAccessoryView = myToolBar;
    
    
    if ([self.optType isEqualToString:@"1"]) {
        
        timeView=[[TimeView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 200)];
        timeView.backgroundColor=[UIColor whiteColor];
        [MYmainScroll addSubview:timeView];
        _da = [[UIDatePicker alloc] init];
        [_da addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        _da.datePickerMode = UIDatePickerModeDate;
        _da.backgroundColor=[UIColor whiteColor];
        
        _da1 = [[UIDatePicker alloc] init];
        [_da1 addTarget:self action:@selector(dateChanged1:) forControlEvents:UIControlEventValueChanged];
        _da1.datePickerMode = UIDatePickerModeTime;
        _da1.backgroundColor=[UIColor whiteColor];
       
        _da2 = [[UIDatePicker alloc] init];
        [_da2 addTarget:self action:@selector(dateChanged2:) forControlEvents:UIControlEventValueChanged];
        _da2.datePickerMode = UIDatePickerModeTime;
        _da2.backgroundColor=[UIColor whiteColor];

                if ([[NSString stringWithFormat:@"%@",  self.bookingDate ] length]>3) {
//                    NSRange range={0,10};
//                    NSString* string =[self.bookingDate substringWithRange:range];
                    timeView.tureDisposeDateTextFied.text= self.bookingDate;
                    timeView.bookingDateLabel.text=self.bookingDate;
                    timeView.bookingTimeLabel.text=self.bookingTime;
                    _da.date =[self dateFromString:timeView.tureDisposeDateTextFied.text ];
               
                    
                    
//                    NSString *originalString = @"a1b2c3d4e5f6g7h8i9j";
//                    
//                    // Intermediate
//                    NSMutableString *numberString = [[NSMutableString alloc] init];
//                    NSString *tempStr;
//                    NSScanner *scanner = [NSScanner scannerWithString:originalString];
//                    NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
//                    
//                    while (![scanner isAtEnd]) {
//                        // Throw away characters before the first number.
//                        [scanner scanUpToCharactersFromSet:numbers intoString:NULL];
//                        
//                        // Collect numbers.
//                        [scanner scanCharactersFromSet:numbers intoString:&tempStr];
//                        [numberString appendString:tempStr];  
//                        tempStr = @"";  
//                    }  
//                    // Result.  
//                    int number = [numberString integerValue];
                    
//                    
//                    NSString*string =@"sdfsfsf-sAdfsdf";
//                    NSRange range = [string rangeOfString:@"-"];//匹配得到的下标
//                    NSLog(@"rang:%@",NSStringFromRange(range));
//                    string = [string substringWithRange:range];//截取范围类的字符串
//                    NSLog(@"截取的值为：%@",string);
//                    
                    
                    if (self.bookingTime.length>8) {
                
                    NSString*string =self.bookingTime;
                    
                    NSArray *array = [string componentsSeparatedByString:@"-"]; //从字符A中分隔成2个元素的数组
                   
                         timeView.tureDisposeTimeTextFied.text=array[0];
                        _da1.date =[self dateFromString1:timeView.tureDisposeTimeTextFied.text ];
                    
                        timeView.tureDisposeTimeTextFied1.text=array[1];
                       _da2.date =[self dateFromString2:timeView.tureDisposeTimeTextFied1.text];
                    }else{
                    
                    
                    }
                }else{
        
               }
        timeView.tureDisposeDateTextFied.textAlignment=NSTextAlignmentCenter;
        timeView.tureDisposeDateTextFied.delegate = self;
        timeView.tureDisposeDateTextFied.inputView = _da;
        timeView.tureDisposeDateTextFied.inputAccessoryView= myToolBar;

        
        timeView.tureDisposeTimeTextFied.textAlignment=NSTextAlignmentCenter;
        timeView.tureDisposeTimeTextFied.delegate = self;
        timeView.tureDisposeTimeTextFied.inputView = _da1;
        timeView.tureDisposeTimeTextFied.inputAccessoryView= myToolBar;
        
       
        timeView.tureDisposeTimeTextFied1.textAlignment=NSTextAlignmentCenter;
        timeView.tureDisposeTimeTextFied1.delegate = self;
        timeView.tureDisposeTimeTextFied1.inputView = _da2;
        timeView.tureDisposeTimeTextFied1.inputAccessoryView= myToolBar;
        view.frame=CGRectMake(0, 210, ScreenWidth, 120);
        
    }else if ([self.optType isEqualToString:@"2"]){
        
        label.text = @"拒绝原因";
    
    }else if ([self.optType isEqualToString:@"3"]){
   
   
    }else if ([self.optType isEqualToString:@"4"]){
        imageView=[[UIView alloc]initWithFrame:CGRectMake(0, 140, ScreenWidth, 145)];
        imageView.backgroundColor=[UIColor whiteColor];
        imageView.layer.borderWidth = 0.40;
        imageView.layer.borderColor = qianhuiColor.CGColor;
        [MYmainScroll addSubview:imageView];
        
        imageArray = [NSMutableArray arrayWithObjects:nil];
        UILabel*labelImage=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth, 44)];
        labelImage.text=@"图片";
        labelImage.textColor=shenhuiColor;
        labelImage.font=[UIFont systemFontOfSize:15];
        [imageView addSubview:labelImage];
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(collectionCellHeight, collectionCellHeight);
        flowLayout.minimumInteritemSpacing = 5;
        flowLayout.minimumLineSpacing = 5;
        flowLayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,label.bottom+10, ScreenWidth, collectionCellHeight+15*2) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        self.collectionView.dataSource=self;
        self.collectionView.delegate=self;
        
        [self.collectionView registerClass:[webCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        [imageView addSubview:self.collectionView];
        


    }

}
-(void)next{

                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSString* Token = [user objectForKey:@"tokenId"];
                NSMutableDictionary *params = [NSMutableDictionary new];
                [params setValue:Token forKey:@"tokenId"];
                [params setValue:self.optType forKey:@"optType"];
    
                if ([self.optType isEqualToString:@"1"]) {
                    [params setValue:timeView.tureDisposeDateTextFied.text forKey:@"acceptConfirmDate"];
                    [params setValue:[NSString stringWithFormat:@"%@-%@",timeView.tureDisposeTimeTextFied.text,timeView.tureDisposeTimeTextFied1.text] forKey:@"acceptConfirmTime"];
                }
    
    if ([self.optType isEqualToString:@"4"]) {
    
       [params setValue:imageList  forKey:@"images"];
    
    }
                [params setValue:tv.text forKey:@"remark"];
                [params setValue:self.orderId forKey:@"orderId"];
                [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
             NSLog(@"params-----------%@", params);
                [HttpRequest requestData:@"Booking/Order/Dispose" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                    if (isSuccess) {
                        NSLog(@"-----------%@", severDataDict.dataDict);
                        if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                            [Global hideProgressHUDInternal:self.view];
                            [_mDelegate update:@""];
                           [self.navigationController popViewControllerAnimated:YES];
    
                        }else{
                            [Global hideProgressHUDInternal:self.view];
                            NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                            [Global showTextHudSub:requestResultStr view:self.view];
                        }}
                    else
                    {
                        [Global hideProgressHUDInternal:self.view];
                        [Global showTextHudSub:severDataDict.resultStr view:self.view];
                    }
                    
                }];



}
-(void)textViewDidChange:(UITextView *)textView
{
    
    if (textView.text.length == 0) {
        [images removeFromSuperview];
        images=[[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 20, 16)];
        images.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
        [tv addSubview:images];
        label.text = @"备注";
        
    }else{
        [images removeFromSuperview];
        label.text = @"";
    }
}
//回收键盘
-(void)OnTapDone{
    [tv resignFirstResponder];
    [timeView.tureDisposeDateTextFied resignFirstResponder];
     [timeView.tureDisposeTimeTextFied resignFirstResponder];
     [timeView.tureDisposeTimeTextFied1 resignFirstResponder];
    
}
-(void)dateChanged1:(UIButton*)sender{
    UIDatePicker* picker = (UIDatePicker*)sender;
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@" HH:mm"];
   
    NSTimeInterval late=[picker.date timeIntervalSince1970]*1;
    NSTimeInterval late1=late+3600;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:late1];

    
    if ([timeView.tureDisposeTimeTextFied isFirstResponder])
    {
        timeView.tureDisposeTimeTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        timeView.tureDisposeTimeTextFied1.text = [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
        
    }else{
        
        timeView.tureDisposeTimeTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        timeView.tureDisposeTimeTextFied1.text = [NSString stringWithFormat:@"%@", [df stringFromDate:date]];
    }
        _da2.date =[self dateFromString2:timeView.tureDisposeTimeTextFied1.text];
}

-(void)dateChanged2:(UIButton*)sender{
    UIDatePicker* picker = (UIDatePicker*)sender;
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@" HH:mm"];
    
    NSTimeInterval late=[picker.date timeIntervalSince1970]*1;
    NSTimeInterval late1=late-3600;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:late1];

    if ([timeView.tureDisposeTimeTextFied1 isFirstResponder])
    {
        timeView.tureDisposeTimeTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:date]];

        timeView.tureDisposeTimeTextFied1.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        
    }else{
        timeView.tureDisposeTimeTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:date]];

        timeView.tureDisposeTimeTextFied1.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
    }
    
    
    _da1.date =[self dateFromString1:timeView.tureDisposeTimeTextFied.text ];
 

}

-(void)dateChanged:(UIButton*)sender{
    UIDatePicker* picker = (UIDatePicker*)sender;
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    if ([timeView.tureDisposeDateTextFied isFirstResponder])
    {
        timeView.tureDisposeDateTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        
    }else{
        
        timeView.tureDisposeDateTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
    }
}
- (NSDate *)dateFromString1:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"HH:mm"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    return destDate;
    
}

- (NSDate *)dateFromString2:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"HH:mm"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    return destDate;
    
}

- (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    return destDate;
    
}



//上传数据
-(void)GO:(UIButton*)sender{
    
    if ([self.optType isEqualToString:@"4"]) {
        [imageList removeAllObjects];
        
        if (imageArray.count>0) {
            [self  upToUpYun];
        }else{
            [self  next];
        }

    }else{
        
     [self  next];
    }
    
}


-(void)upToUpYun
{
       NSLog(@"imageList--------－－－－%@",imageArray);
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    for (int i=0; i<imageArray.count; i++) {
        
        UIImage *portraitImg = [[UIImage alloc]init];
        portraitImg = [self imageByScalingToMaxSize:imageArray[i]];
        
        UpYun *uy = [[UpYun alloc] init];
        uy.successBlocker = ^(id data)
        {
            
            
            NSString *imageURL;
            NSString *imageWIDTH;
            NSString *imageHEIGHT;
            imageURL=[data objectForKey:@"url"];
            imageWIDTH=[data objectForKey:@"image-width"];
            imageHEIGHT=[data objectForKey:@"image-height"];
            NSMutableDictionary *upYunImageDict=[NSMutableDictionary dictionary];
            [upYunImageDict setObject:imageURL forKey:@"imageUrl"];
            [upYunImageDict setObject:imageWIDTH forKey:@"imageWidth"];
            [upYunImageDict setObject:imageHEIGHT forKey:@"imageHeight"];
            
            [imageList addObject:upYunImageDict];
            

            if (imageList.count==imageArray.count) {
                
                [Global hideProgressHUDInternal:self.view];
                NSLog(@"imageList--------－－－－%@",imageList);
               [self  next];
            }
            
        };
        uy.failBlocker = ^(NSError * error)
        {
            [Global hideProgressHUDInternal:self.view];
            
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"上传失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            NSLog(@"%@",error);
        };
        uy.progressBlocker = ^(CGFloat percent, long long requestDidSendBytes)
        {
            
        };
        
        [uy uploadFile:portraitImg saveKey:[self getSaveKey]];
        
    }
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (imageArray.count>=10) {
        ArrayCount =9;
    }else{
    
        ArrayCount =imageArray.count;
    }
    
    return ArrayCount+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * string = @"cell";
    webCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:string forIndexPath:indexPath];
    
    
    if (indexPath.row == imageArray.count) {
        if (imageArray.count==10) {
            
            cell.imgView.image = imageArray[indexPath.row];

        }else{
        cell.imgView.image = [UIImage imageNamed:@"tianjiatupian"];
        }
   
    }else{
        cell.imgView.image = imageArray[indexPath.row];
    }
    
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
      [tv resignFirstResponder];
    if (indexPath.item == imageArray.count)
    {
        
        
        UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
        [actionSheet showInView:self.view];
    }
    else
    {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"确定删除" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.tag = indexPath.row;
        [alertView show];
    }
    
    [collectionView reloadData];
    
}
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            controller.allowsEditing = YES;
            //            controller.showsCameraControls=true;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            controller.allowsEditing = YES;
            //            controller.showsCameraControls=NO;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 1)
    {
        
        [imageArray removeObjectAtIndex:alertView.tag];
        [self.collectionView reloadData];
        [self customLayout];
        
    }
}

//图像选取器的委托方法，选完图片后回调该方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage* image = [info valueForKey:UIImagePickerControllerEditedImage];
    if (image != nil)
    {
        [imageArray addObject:image];
        [self.collectionView reloadData];
        
       
        [self customLayout];
        
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)customLayout
{
    
    int numberOfLines = (int)ceil([self collectionView:self.collectionView numberOfItemsInSection:0] / 4.0);
    
    CGRect frame = self.collectionView.frame;
    frame.size.height = numberOfLines *collectionCellHeight + (numberOfLines - 1) * 5 + 15*2;
    self.collectionView.frame = frame;
    imageView.frame=CGRectMake(0, 140, ScreenWidth, self.collectionView.bottom+15);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSString * )getSaveKey {
    /**
     *	@brief	方式1 由开发者生成saveKey
     */
    NSDate *d = [NSDate date];
    return [NSString stringWithFormat:@"/%d/%d/%.0f.png",[self getYear:d],[self getMonth:d],[[NSDate date] timeIntervalSince1970]];
    
    /**
     *	@brief	方式2 由服务器生成saveKey
     */
    //    return [NSString stringWithFormat:@"/{year}/{mon}/{filename}{.suffix}"];
    
    /**
     *	@brief	更多方式 参阅 http://wiki.upyun.com/index.php?title=Policy_%E5%86%85%E5%AE%B9%E8%AF%A6%E8%A7%A3
     */
    
}
#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:20 view:self.view];
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return nil;
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}
#define ORIGINAL_MAX_WIDTH 420.0f
#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


- (int)getYear:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    return year;
}

- (int)getMonth:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int month = [comps month];
    return month;
}
-(UIImage *)imageCompress:(UIImage *)image11
{
    UIImage *comImage=image11;
    NSData * sendImageData = UIImageJPEGRepresentation(comImage, 1.0);
    NSUInteger sizeOrigin = [sendImageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB >400) {
        float a = 800.0000;
        float b = (float)sizeOriginKB;
        float q = sqrtf(a / b);
        
        CGSize sizeImage = [comImage size];
        CGFloat widthSmall = sizeImage.width * q;
        CGFloat heighSmall = sizeImage.height * q;
        CGSize sizeImageSmall = CGSizeMake(widthSmall, heighSmall);
        
        UIGraphicsBeginImageContext(sizeImageSmall);
        CGRect smallImageRect = CGRectMake(0, 0, sizeImageSmall.width, sizeImageSmall.height);
        [image11 drawInRect:smallImageRect];
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        NSData *dataImage = UIImageJPEGRepresentation(smallImage, 1.0);
        sendImageData = dataImage;
        NSLog(@"11111111%f",sizeImageSmall.width);
        NSLog(@"11111111%f",sizeImageSmall.height);
        comImage= smallImage;
        // [_imageview1.image retain];
    }
    return comImage;
}

@end
